<?php

namespace app\backend\service;
use app\backend\model\AdminModel;
use app\backend\model\RoleModel;
use app\backend\validate\AdminValidate;
use app\common\RootException;
use app\common\RootService;

class LoginService extends RootService
{
    /**
     * 用户登录
     * @param array $params
     * @return array
     * @throws RootException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(array $params)
    {
        $tokenExpire = env('app.admin_token_expire', 240) * 60;
        // 基础校验
        $validate = new AdminValidate();
        if (!$validate->scene('login')->check($params)) {
            $this->errorException($validate->getError());
        }
        // 图形验证码校验
        $this->checkImgCode($params['imgCode'], $params['imgKey'], true);
        // 用户名密码校验
        $where = ['admin_name' => $params['adminName'], 'password' => $this->encAdminPwd($params['password'])];
        if (!$adminInfo = AdminModel::where($where)->find()) {
            throw new RootException('用户名或密码不正确');
        }
        // 禁用账号
        empty($adminInfo['state']) && $this->errorException('您的账号已被系统禁用，请联系管理员!!!');
        // 获取token
        $accessToken = $this->issueAdminToken($adminInfo['id']);
        // 设置COOKIE
        cookie('accessToken', $accessToken, $tokenExpire);
        // 更新登录时间
        $adminInfo->login_time = date('Y-m-d H:i:s');
        $adminInfo->save();
        // 获取权限
        $adminInfo->authMenuIds = RoleModel::where(['id' => $adminInfo['role_id']])->value('menu_ids');
        // 缓存用户信息
        cache(md5($accessToken . 'admin' . $adminInfo['id']), $adminInfo->toArray(), $tokenExpire);
        // 返回token
        return ['accessToken' => $accessToken, 'msg' => '登录成功'];
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        // 清除缓存
        cache(md5(cookie('accessToken') . adminInfo('id')), null);
        // 清除Cookie
        cookie('accessToken', null);
        // 跳转到登录页面
        return redirect(url('Login/index'));
    }
}